package com.shiyu.system.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shiyu.common.core.constants.UserIdentity;
import com.shiyu.common.core.domain.R;
import com.shiyu.common.core.enums.ResultCode;
import com.shiyu.common.security.exception.ServiceException;
import com.shiyu.common.security.service.TokenService;
import com.shiyu.system.domain.SysUser;
import com.shiyu.system.domain.SysUserSaveDTO;
import com.shiyu.system.mapper.SysUserMapper;
import com.shiyu.system.service.ISysUserService;
import com.shiyu.system.utils.BcryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

   @Autowired
    private  TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret;
    @Override
    public R<String> login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper<>();
        SysUser sysUser=sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getPassword,SysUser::getUserId).eq(SysUser::getUserAccount,userAccount));
        R loginResult=new R();
        if(sysUser==null){
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(BcryptUtils.matchesPassword(password,sysUser.getPassword())){
          String token=tokenService.createToken(sysUser.getUserId(),secret,UserIdentity.ADMIN.getValue());
          return R.ok(token);
        }
        return R.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
//        将dto转为实体.
//        首先判断这个账户是否存在
        List<SysUser> sysUsers=sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount,sysUserSaveDTO.getUserAccount()));
        if(CollectionUtil.isNotEmpty(sysUsers)){
            throw  new ServiceException(ResultCode.AILED_USER_EXISTS);
        }
        SysUser sysUser=new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BcryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
//        获取当前用户的id
       return sysUserMapper.insert(sysUser);
    }


}

